﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using Tauren.File.DLL.FolderDLL;
using Tauren.File.DLL.Resouces;
using Tauren.File.Entity.Config;
using Tauren.File.Entity.Const;
using Tauren.File.Entity.Enum;
using Tauren.File.Entity.Global;
using Tauren.File.Entity.Input;
using Tauren.File.Entity.Model;
using Tauren.File.Entity.Output;
using Tauren.File.Infrastructure.Common;
using Tauren.File.Infrastructure.Globals;

namespace Tauren.File.Service.FileFolderBLL
{
    public class FolderServices : Base.BaseService, IFolderServices
    {
        private IFileFolderBusiness business;
        public FilePath filePath;
        public FolderServices(IConfiguration configuration, IFileFolderBusiness _business, IConnectionBLLBase connectionBLL, IMenuResourcesBusiness resourcesBusiness) : base(_business, connectionBLL, resourcesBusiness)
        {
            this.business = _business;
            this.ResourcesInfo = this.GetResources(GlobalConst.RESOURCES_FLAG_MODULE_FILEFOLDER_KEY);
            this.JudePrmission(GlobalConst.RESOURCES_FLAG_MODULE_FILEFOLDER_KEY.ToLower());
            ///获取配置文件中的数据
            filePath = configuration.Get<ApiVersionsConfig>().FilePath;
        }

        public IResponseMessage Add(FileFolder_InPut data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            FileFolder fileFolder;
            ToModel(data, out fileFolder);
            var codes = business.IsFolderRepeat(fileFolder);
            if (codes) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            fileFolder.Code = Guid.NewGuid().ToString().Replace("-", "").Trim();
            if (fileFolder.ParentId == 0)
            {
                fileFolder.Path = $"/{fileFolder.Code.Trim()}";
            }
            else
            {
                FileFolder parentFolder = business.Get<FileFolder>(fileFolder.ParentId);
                if (parentFolder is null) fileFolder.Path = $"/{fileFolder.Code.Trim()}";
                else fileFolder.Path = $"{parentFolder.Path}/{fileFolder.Code.Trim()}";
            }
            fileFolder.Enable = true;
            fileFolder.Sequence = business.GetSeq();
            fileFolder.Creator = Global.EmpId;
            fileFolder.Modifier = Global.EmpId;
            fileFolder.Creatdate = DateTime.Now;
            fileFolder.Modifdate = DateTime.Now;
            if (business.Add<FileFolder>(fileFolder) > 0)
                return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
            else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
        }

        public IResponseMessage Config(string PageType)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            List<OutPutConfig> Fields = new List<OutPutConfig>();

            OutPutConfig config = new OutPutConfig();
            Dictionary<object, object> rule = new Dictionary<object, object>();

            #region 中文名
            config = new OutPutConfig();
            config.Label = this.CommonText("thcnname");
            config.FieldKey = "cnName";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_FILEFOLDER_KEY.ToLower();
            config.ControlType = ControlType.textarea;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                rule.Add("required", true);
                rule.Add("message", this.CommonText("fieldsrequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 100);
                rule.Add("message", this.Resources("fieldnamemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion

            #region 英文名
            config = new OutPutConfig();
            config.Label = this.CommonText("thenname");
            config.FieldKey = "enName";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_FILEFOLDER_KEY.ToLower();
            config.ControlType = ControlType.textarea;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                rule.Add("required", true);
                rule.Add("message", this.CommonText("fieldsrequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 200);
                rule.Add("message", this.Resources("fieldennamemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion      
            return Fields.Succeed();
        }

        public IResponseMessage Delete(int AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            FileFolder dbModble = business.Get<FileFolder>(AutoID);
            if (dbModble is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            dbModble.Enable = false;
            dbModble.Modifier = Global.EmpId;
            dbModble.HaveDelete = true;
            dbModble.Modifdate = DateTime.Now;
            if (business.Update<FileFolder>(dbModble))
                return "".OnSucceed(this.Resources(GlobalErrorType.GLOBAL_DELETE_SUCCESSINFO));
            else return GlobalErrorType.GLOBAL_DELETE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DELETE_FAILURE));
        }

        public IResponseMessage Edit(FileFolder_InPut data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            FileFolder fileFolder;
            ToModel(data, out fileFolder);
            var codes = business.IsFolderRepeat(fileFolder);
            if (codes) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            FileFolder dbModble = business.Get<FileFolder>(fileFolder.AutoId);
            if (dbModble is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            if (fileFolder.ParentId == 0)
            {
                fileFolder.Path = $"/{fileFolder.Code.Trim()}";
            }
            else
            {
                FileFolder parentFolder = business.Get<FileFolder>(fileFolder.ParentId);
                if (parentFolder is null) fileFolder.Path = $"/{fileFolder.Code.Trim()}";
                else fileFolder.Path = $"{parentFolder.Path}/{fileFolder.Code.Trim()}";
            }
            fileFolder.Creator = dbModble.Creator;
            fileFolder.Modifier = Global.EmpId;
            fileFolder.Creatdate = dbModble.Creatdate;
            fileFolder.Modifdate = DateTime.Now;
            if (business.Update<FileFolder>(fileFolder))
                return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
            else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
        }

        public IResponseMessage Enable(int AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            FileFolder dbModble = business.Get<FileFolder>(AutoID);
            if (dbModble is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            dbModble.Enable = !dbModble.Enable;
            dbModble.Modifier = Global.EmpId;
            dbModble.Modifdate = DateTime.Now;
            if (business.Update<FileFolder>(dbModble))
                return "".OnSucceed(this.CommonText(dbModble.Enable ? GlobalErrorType.GLOBAL_ENABLE_SUCCESSINFO : GlobalErrorType.GLOBAL_DISABLE_SUCCESSINFO));
            else return dbModble.Enable ? GlobalErrorType.GLOBAL_ENABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_ENABLE_FAILURE)) : GlobalErrorType.GLOBAL_DISABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DISABLE_FAILURE));
        }

        public IResponseMessage Get(int AutoID)
        {
            FileFolder organization = business.Get<FileFolder>(AutoID);
            FileFolder_OutPut _OutPut = new FileFolder_OutPut();
            ToViewModel(organization, out _OutPut);
            if (_OutPut is null) return new FileFolder_OutPut().Succeed();
            return _OutPut.Succeed();
        }

        public IResponseMessage Pages(QueryModel queryModel)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            TableListModel<PageDocumentCenterTable> tableListModel = new TableListModel<PageDocumentCenterTable>();
            List<TableListHeaderModele> Headers = new List<TableListHeaderModele>();
            Headers.Add(new TableListHeaderModele() { Key = "rowNo", Name = this.CommonText("rowno"), Width = 50, Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "autoId", Name = this.Resources("orgid"), Width = 120, Hide = true, Fixed = true, Type = "primary_key", });
            Headers.Add(new TableListHeaderModele() { Key = "cnName", Name = this.CommonText("thcnname"), Type = "primary_name", Hyperlink = true, IsOperation = true, SorTable = SortType.custom.ToString(), Fixed = true, Width = 360,Filter=true });
            Headers.Add(new TableListHeaderModele() { Key = "enName", Name = this.CommonText("thenname"), Type = "primary_name", Hyperlink = true, SorTable = SortType.custom.ToString(), Fixed = true, Width = 360, Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "dic_FileType", Name = this.Resources("thfiletype"), Align = "center", IsTag = true, Width = 180 });
            Headers.Add(new TableListHeaderModele() { Key = "dic_OrgType", Name = this.Resources("thdicorgtype"), Align = "center", IsTag = true, Width = 180 });
            Headers.Add(new TableListHeaderModele() { Key = "ext", Name = this.CommonText("thfileext"), Width = 160, Align = "center", Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "size", Name = this.CommonText("thfilesize"), Width = 160, Align = "center", Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "currentVersion", Name = this.CommonText("thfilesizeversion"), Width = 160, Align = "center", Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Enable", Name = CommonText("thstate"), IsTag = true, Width = 100, Align = "center", SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creator", Name = CommonText("diccreator"), Width = 120, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creatdate", Name = CommonText("diccreatdate"), Width = 160, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "action", Name = "操作", Width = 160, Align = "center" });
            long Total = 0;
            List<PageDocumentCenterTable> pageOrganizationTables = business.Pages(queryModel, out Total);
            if (pageOrganizationTables.Any())
            {
                pageOrganizationTables.ForEach(o =>
                {
                    o.Dic_OrgType = string.IsNullOrEmpty(o.OrgType) ? "" : this.CommonText($"file{((FolderType)int.Parse(o.OrgType)).ToString()}");
                    o.Dic_FileType = this.CommonText($"file{((TextType)o.FileType).ToString()}");
                    o.Dic_Enable = CommonText(o.Enable ? GlobalConst.RESOURCES_CONTENT_ENABLE_KEY : GlobalConst.RESOURCES_CONTENT_DISABLE_KEY);
                    o.Dic_Creator = EmpDictionary.ContainsKey(o.Creator) ? EmpDictionary[o.Creator] : "";
                    o.Dic_Creatdate = o.Creatdate.Value.ToString(GlobalConst.DATE_FORMAT_SECONDS);
                    o.Row_Style = o.Enable ? "" : "danger";
                    o.Size = string.IsNullOrEmpty(o.Size) ? "" : double.Parse(o.Size).CovertToGb();
                    o.FileUri = string.IsNullOrEmpty(o.FileUri) ? "" : $"{filePath.FileApiUrl}{o.FileUri}";
                    o.Operations = new List<SystemButton>();
                    if (o.FileType != 0)
                    {
                        o.CNName = $"{o.CNName}.{o.Ext}";
                        o.ENName = $"{o.ENName}.{o.Ext}";
                    }
                    if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
                    {
                        BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.edit);
                        if (o.FileType == 1 || o.FileType == 2 || o.FileType == 3)
                            BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.oneditdoc);
                        BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.detaile);
                        if (o.FileType == 1 || o.FileType == 2 || o.FileType == 3)
                            BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.ondetaildoc);
                        if (o.FileType != 0)
                            BuliderButtons(o.Operations, $"{(Global.IsChinese ? o.CNName : o.ENName)}", o.AutoId, ButtomType.download);
                        BuliderButtons(o.Operations, o.FileType + "", o.AutoId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.delete);
                    }
                    else
                    {
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.edit.ToString()))
                            BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.edit);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.oneditdoc.ToString()) && (o.FileType == 1 || o.FileType == 2 || o.FileType == 3))
                            BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.oneditdoc);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.detaile.ToString()))
                            BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.detaile);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.ondetaildoc.ToString()) && (o.FileType == 1 || o.FileType == 2 || o.FileType == 3))
                            BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.ondetaildoc);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.download.ToString()) && o.FileType != 0)
                            BuliderButtons(o.Operations, $"{(Global.IsChinese ? o.CNName : o.ENName)}", o.AutoId, ButtomType.download);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && (o.Value == ButtomType.enable.ToString() || o.Value == ButtomType.disable.ToString())))
                            BuliderButtons(o.Operations, o.FileType + "", o.AutoId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.delete.ToString()))
                            BuliderButtons(o.Operations, o.FileType + "", o.AutoId, ButtomType.delete);
                    }
                });
            }
            tableListModel.Body = pageOrganizationTables;
            tableListModel.Total = Total;
            tableListModel.Header = Headers;
            if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
            {
                BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
                if (queryModel.paramters.Any(o => o.Label.ToLower() == "folderid"))
                {
                    var floder = queryModel.paramters.FirstOrDefault(P => P.Label.ToLower() == "folderid");
                    if (!string.IsNullOrEmpty(floder.Value + "") && (floder.Value + "") != "0")
                    {
                        BuliderButtons(tableListModel.Operations, "", 0, ButtomType.upload);
                    }
                }
            }
            else
            {
                if (Buttons.Any(o => o.Value == ButtomType.add.ToString()))
                    BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
                if (queryModel.paramters.Any(o => o.Label.ToLower() == "folderid"))
                {
                    var floder = queryModel.paramters.FirstOrDefault(P => P.Label.ToLower() == "folderid");
                    if (!string.IsNullOrEmpty(floder.Value + "") && (floder.Value + "") != "0")
                    {
                        if (Buttons.Any(o => o.Value == ButtomType.upload.ToString()))
                            BuliderButtons(tableListModel.Operations, "", 0, ButtomType.upload);
                    }
                }
            }
            return tableListModel.Succeed();
        }
    }
}
